<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="600px"
    draggable
    :before-close="handleClose"
    @open="handleOpen">
    <el-form ref="formRef" :model="form" :rules="rules" size="small" label-width="100px">
      <el-form-item label="样本编码" prop="sampleCode">
        <el-input v-model.trim="form.sampleCode" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input v-model.trim="form.patientName" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="项目名" prop="projectName">
        <el-input v-model.trim="form.projectName" class="input-width"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { awaitWrap, elFormValidate } from '@/utils'
import { SUCCESS_CODE } from '@/constants'
import { useDialogCommonData, emitBaseEventList } from '@/composables/dialog-common'
import { submitSampleInfo } from '@/api/sample-management'

// ---------------------props-------------------
const props = defineProps({
  visible: Boolean, // 可见性
  pdata: { // 数据，同defaultForm表单
    type: Object,
    default () {
      return null
    }
  }
})

// emit
const emit = defineEmits([...emitBaseEventList])

// form组件实例
const formRef = ref() // this.$refs.form

// ---------------------el-Dialog组件需要一些参数-------------------
const { dialogVisible, handleClose } = useDialogCommonData(props, emit)
const title = ref('') // 组件title
// 打开组件
const handleOpen = () => {
  title.value = props.pdata ? '编辑样本' : '新增样本'
  initForm()
}

// ---------------------form 内容-------------------
// 默认表格内容
const defaultForm = {
  fid: '',
  sampleCode: '', // 样本编号
  patientName: '',
  projectName: ''
}
const form = ref({ ...defaultForm })
const rules = ref({
  sampleCode: [
    { required: true, message: '请输入', trigger: 'blur' }
  ]
})
// 初始化form
const initForm = () => {
  form.value = props.pdata ? { ...props.pdata } : { ...defaultForm }
  nextTick(formRef.value.clearValidate)
}
// 提交参数loading
const submitLoading = ref(false)

// 点击提交
const handleConfirm = async () => {
  await elFormValidate(formRef.value)
  const f = form.value
  const params = {
    sampleCode: f.sampleCode,
    fid: f.fid
  }
  submitLoading.value = true
  // 提交样本信息
  const { res } = await awaitWrap(submitSampleInfo(params))
  if (res?.statusCode === SUCCESS_CODE) {
    ElMessage.success('提交成功')
    emit('dialogConfirmEvent')
    dialogVisible.value = false
  }
  submitLoading.value = false
}

</script>

<style scoped lang="scss">
.input-width{
  width: 300px;
}
</style>
